<template>
  <div class="common-layout">
    <el-container>
      <el-container>
        <el-aside width="300">
          <vxe-grid ref="taskListGrid" v-bind="gridOptions1" size="mini" @current-change="currentChangeEvent">
            <template #toolbar_buttons>
              <vxe-button @click="getTaskList">刷新</vxe-button>
              <vxe-button @click="newtask">新建</vxe-button>
              <vxe-button @click="gridOptions1.align = 'right'">删除</vxe-button>
            </template>
          </vxe-grid>
        </el-aside>
        <el-container>
          <el-main>
            <vxe-form :data="form" title-align="right" title-width="100" size="mini">
              <vxe-form-item field="name" title="名称" :span="8" :item-render="{}">
                <template #default="{ data }">
                  <vxe-input v-model="data.name" placeholder="请输入名称"></vxe-input>
                </template>
              </vxe-form-item>
              <vxe-form-item title="启用" field="isActive" :span="16"
                             :item-render="{name: '$switch', props:{openLabel:'是',openValue:1,closeLabel:'否',closeValue:0}}"
                             title-overflow="ellipsis"></vxe-form-item>
                <vxe-form-item title="选择模板" field="template" :item-render="{}" span="14">
                    <template #default="{ data }">
                        <vxe-select  v-model="data.template" filterable clearable placeholder="选择模板" multiple>
                            <vxe-option
                                    v-for="item in templates"
                                    :key="item.id"
                                    :label="item.title"
                                    :value="item.code"
                            />
                        </vxe-select >


                    </template>
                </vxe-form-item>
              <vxe-form-item field="type" title="关联方式" :span="10" :item-render="{}">
                <template #default="{ data }">
                    <vxe-checkbox-group v-model="data.type">
                        <vxe-checkbox label="api" content="数据接口抛入"></vxe-checkbox>
                        <vxe-checkbox label="excel" content="模板Excel导入"></vxe-checkbox>
                    </vxe-checkbox-group>
                </template>
              </vxe-form-item>

              <vxe-form-item field="tm" title="执行时机" :span="8" :item-render="{}">
                <template #default="{ data }">
                    <vxe-checkbox-group v-model="data.tm">
                        <vxe-checkbox :label="1" content="写入前"></vxe-checkbox>
                        <vxe-checkbox :label="2" content="写入后"></vxe-checkbox>
                    </vxe-checkbox-group>
                </template>
              </vxe-form-item>

            </vxe-form>
              <vxe-toolbar>
                  <template #buttons>
                      <vxe-button icon="vxe-icon-square-plus" @click="insertProcEvent()">新增处理步骤</vxe-button>
                  </template>
              </vxe-toolbar>
              <vxe-table
                      border
                      show-overflow
                      ref="procGrid"
                      height="300"
                      :column-config="{resizable: true}"
                      :row-config="{isHover: true}"
                      :data="processData">
                  <vxe-column type="seq" width="60"></vxe-column>
                  <vxe-column field="title" title="步骤说明"></vxe-column>
                  <vxe-column field="condition" title="执行条件" ></vxe-column>
                  <vxe-column field="todo" title="执行动作"></vxe-column>
                  <vxe-column title="操作" width="100" show-overflow>
                      <template #default="{ row }">
                          <vxe-button type="text" icon="vxe-icon-edit" @click="editProcEvent(row)"></vxe-button>
                          <vxe-button type="text" icon="vxe-icon-delete" @click="removeProcEvent(row)"></vxe-button>
                      </template>
                  </vxe-column>
              </vxe-table>
              <div>
            </div>
          </el-main>
        </el-container>
      </el-container>
    </el-container>
      <processEdit ref="PE" :v-model="procFormData" ></processEdit>
  </div>
</template>

<script>
import {defineComponent, onBeforeMount, reactive, toRefs,ref} from 'vue'
import {listLkOdatabase} from '/@/api/linkoo/form/lkDataRules'
import {taskEdit, taskList, taskOperation, taskTestSql,taskTest} from '/@/api/linkoo/task/index'
import {getDatasource} from "/@/api/linkoo/templates";
import XEUtils from 'xe-utils'
import processEdit from './processEdit.vue'
import {ElMessage} from 'element-plus'
import {getUserList} from "/@/api/system/user";
//定义变量
export default defineComponent({
  name: "process",components:{processEdit},
  setup() {
    const procGrid = ref(null)
    const PE = ref(null)
    const yj = ref(null)

    let state = reactive({
        windowHeight: document.documentElement.clientHeight,
        ToFields: [],
        title: '新增',
        templates: [],
        tables: [],
        showProcEdit: false,
        submitLoading: false,
        selectRow: null,
        fields: [],
        users: [],
        procFormData: {},
        processData: [],
        DB: [{label: '本地数据库', value: ''}],
        datatype: [{label: '文本', value: 'Text'}, {label: '数字', value: 'Number'}, {label: '日期',value: 'Date'}, {label: '表格', value: 'Table'}],

        doType:[{value: 'sendMsg', title: '发送通知'},{value: 'upData', title: '更新数据'},{value: 'sendData', title: '推送数据'},{value: 'workFlow', title: '发起流程'}],
        form: {id: 0, tm:[],type:[]},
    })
    const gridOptions1 = reactive({
      border: true,
      height: document.documentElement.clientHeight - 200,
      align: null,
      rowConfig: {isCurrent: true, isHover: true},
      columnConfig: {
        resizable: true
      },
      columns: [
        {type: 'seq', width: 45},
        {field: 'name', width: 120, title: '名称'},
        {field: 'isActive', title: '启用', width: 50, showHeaderOverflow: true},
      ],
      toolbarConfig: {
        slots: {
          buttons: 'toolbar_buttons'
        }
      },
      data: []
    })

    const getDatabase = () => {
      listLkOdatabase({pageNum: 1, pageSize: 1000}).then(res => {
        if (res.data.list) {
          res.data.list.forEach(row => {
            state.DB.push({label: row['oDataName'] + ' ' + row['memo'], value: row['oDataName']})
          })
        }

      })
      getDatasource().then(res => {
        state.templates = res.data.list.find(item => item.id === 1).children

      })
      getUserList({pageNum: 1, pageSize: 1000,}).then(res => {
        state.users = res.data.userList.map(row=>{
          row.id=XEUtils.toString(row.id)
          return row
        })
      })
    }
    const getTaskList = () => {
      taskList({pageNum: 1, pageSize: 1000}).then(res => {
        if (res.data) {
          gridOptions1.data = res.data
        }
      })
    }
    const insertProcEvent=()=>{
        state.procFormData = {
            name: '',
            nickname: '',
            role: '',
            sex: '',
            age: '',
            num: '',
            checkedList: [],
            flag1: '',
            date3: '',
            address: ''
        }
        state.selectRow = null
        PE.value.show=true
    }
    const removeProcEvent=()=>{

    }
    const updateProcessRow=()=>{

    }
    const editProcEvent=()=>{

    }
    const submitProcEvent=()=>{

    }
    const newtask = () => {
      XEUtils.objectEach(state.form, (val, key) => {
        state.form[key] = null
      })

      state.form.id = 0
      state.form.ext = {}
    }
    const onSubmit = () => {
      if(state.form.ext.type===1){
        state.form.ext.filter=yj.value.getTableData().fullData
      }
      taskEdit(state.form).then(res => {
        if (res.code === 0) {
          ElMessage.success("任务保存成功!")
        } else {
          ElMessage.error("任务保存失败:" + res.message)
        }
        getTaskList()
      })
    }
    const changetable = (value) => {
      state.tables = XEUtils.find(state.templates, item => item.code === value).children
    }
    const changefield = (value) => {
      state.fields = XEUtils.find(state.tables, item => item.tableName === value).Fields
    }
    const gettestSql = () => {
      taskTestSql({id: state.form.id}).then(res => {
        console.log(res)
      })
    }
    const dotaskTest = () => {
      taskTest( state.form.id).then(res => {
        console.log(res)
      })
    }
    const OperationTask = (status) => {
      if (state.form.id === 0) {
        ElMessage.error("请先选择任务")
        return
      }
      taskOperation({id: state.form.id, status: status}).then(res => {
        console.log(res)
      })
    }
    const remove = () => {
      console.log('submit!')
    }
    const insertEvent = async () => {
      const $table = yj.value
      const record = {field: '', type: '', value: ''}
      const {row: newRow} = await $table.insert(record)
      await $table.setEditCell(newRow, 'name')
    }
    const deleteRowEvent = (row) => {
      const $table = yj.value
      $table.remove(row)
    }

    const currentChangeEvent = ({row}) => {
      const data = XEUtils.clone(row, true)
      data['ext'] = XEUtils.toStringJSON(data['ext'])
      state.form = data
      state.activeName=state.form.type
      if (state.form.type==='D'){
        changetable(state.form.ext.template)
        changefield(state.form.ext.table)
      }
    }
    onBeforeMount(() => {
      getDatabase()
      getTaskList()
    })

    return {
      ...toRefs(state),
      gridOptions1,
      yj,procGrid,PE,
      onSubmit,
      gettestSql,
      newtask,
      getTaskList,
      currentChangeEvent,submitProcEvent,
      remove,insertProcEvent,editProcEvent,removeProcEvent,updateProcessRow,
      changetable, changefield, insertEvent, deleteRowEvent,dotaskTest,
      OperationTask}
  }
})
</script>

<style scoped>

</style>